package eudjok
import twitter4j.Status
import twitter4j.Twitter
import twitter4j.TwitterException
import twitter4j.TwitterFactory
import twitter4j.http.AccessToken
import twitter4j.http.RequestToken
import twitter4j.User

class DjController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [djInstanceList: Dj.list(params), djInstanceTotal: Dj.count()]
    }

    def create = {
		User usuario = session.userT
        def djInstance = new Dj()
        djInstance.properties = params
		djInstance.nomeUsuario = usuario.getScreenName()
		djInstance.bio = usuario.getDescription()
        return [djInstance: djInstance]
    }

    def save = {
		User usuario = session.userT
        def djInstance = new Dj(params)
		djInstance.twitter = usuario.getId()
		def arquivo = request.getFile('arquivo')
		if(!arquivo.isEmpty()){
			String arquivoNome = arquivo.getOriginalFilename()
			String path = "web-app/img/"+djInstance.twitter+"/"
			File file = new File(path)
			file.mkdir()
			djInstance.foto = "img/"+djInstance.twitter+"/"+arquivoNome
			path = path+"/"+arquivoNome
			arquivo.transferTo( new File(path))
		}
		
        if (djInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'dj.label', default: 'Dj'), djInstance.id])}"
            session.dj = djInstance
			redirect(controller:'home',action:'index')
			//redirect(action: "show", id: djInstance.id)
        }
        else {
            render(view: "create", model: [djInstance: djInstance])
        }
    }

    def show = {
        def djInstance = Dj.get(params.id)
        if (!djInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'dj.label', default: 'Dj'), params.id])}"
            redirect(action: "list")
        }
        else {
            [djInstance: djInstance]
        }
    }

    def edit = {
        def djInstance = Dj.get(session.dj.id)
        if (!djInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'dj.label', default: 'Dj'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [djInstance: djInstance]
        }
    }

    def update = {
        def djInstance = Dj.get(params.id)
		def arquivo = request.getFile('arquivo')
		if(!arquivo.isEmpty()){
			String arquivoNome = arquivo.getOriginalFilename()
			String path = "web-app/img/"+djInstance.twitter+"/"
			File file = new File(path)
			file.mkdir()
			djInstance.foto = "img/"+djInstance.twitter+"/"+arquivoNome
			path = path+"/"+arquivoNome
			arquivo.transferTo( new File(path))
		}
        if (djInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (djInstance.version > version) {
                    
                    djInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'dj.label', default: 'Dj')] as Object[], "Another user has updated this Dj while you were editing")
                    render(view: "edit", model: [djInstance: djInstance])
                    return
                }
            }
            djInstance.properties = params
            if (!djInstance.hasErrors() && djInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'dj.label', default: 'Dj'), djInstance.id])}"
                redirect(controller:'home',action:'index')
				//redirect(action: "show", id: djInstance.id)
            }
            else {
                render(view: "edit", model: [djInstance: djInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'dj.label', default: 'Dj'), params.id])}"
   			redirect(action: "list")
        }
    }

    def delete = {
        def djInstance = Dj.get(params.id)
        if (djInstance) {
            try {
                djInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'dj.label', default: 'Dj'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'dj.label', default: 'Dj'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'dj.label', default: 'Dj'), params.id])}"
            redirect(action: "list")
        }
    }
    def login = {
        // Procura o usuario na base de dados
        def dj = Dj.findByEmailAndSenha(params.email,params.senha)
        if (dj) {
            // Abre a session do usuário
            session.dj = dj
            // Redireciona para a sua devida página inicial dependendo do seu tipo
              redirect(uri:"/home/")
        } else {
            flash['error']="${message(code:'error.login.incorreto')}"
            redirect(uri:'')
        }
    }    
    def logout = {
        session.dj = null
		session.countPlayer = null
        flash['message'] = "${message(code:'info.logout.sucesso')}"
        redirect(uri:'')
    }    

    def perfil = {
		def djInstanceList= Dj.findByNomeUsuario(params.dj)
		def djOuvintes= Dj.findById(djInstanceList.id).ouvintes
		def playList= Musica.findAllByDj(djInstanceList)
		def setListInstanceList= SetList.findAllByDj(djInstanceList, [max:5, sort:"id", order:"desc"])
		def setListInstanceTotal= SetList.count()
		
		[djInstanceList:djInstanceList,djOuvintes:djOuvintes,playList:playList,setListInstanceList:setListInstanceList,setListInstanceTotal:setListInstanceTotal]
    }
	def py = { 
		
		def djInstance = Dj.findByNomeUsuario(params.dj)
		def playList= Musica.findAllByDj(djInstance)
		if(playList.size==session.countPlayer+1){session.countPlayer=0}
		else {session.countPlayer = session.countPlayer + 1}
		render(template:"/common/perfil/youtubePlayer2", model:[playList2:playList,'i':session.countPlayer])
	}
}
